package mspbots.xero.client.oauth;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.xero.client.core.AbstractToolsUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * com.mspbots.doctor.core.RedirectAuthController
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/19
 */
@Log4j2
@Controller
@RequestMapping("oauth")
@RequiredArgsConstructor
public class AuthController extends AbstractToolsUtil {

    private final AuthService authService;

    @ResponseBody
    @GetMapping("authorize")
    public Mono<TokenState> authorize(@RequestParam String state, @RequestParam String code) {
        return this.authService.authToken(TokenState.withDefault(Long.parseLong(state)), code);
    }

    @GetMapping("redirect")
    public Mono<String> redirect(@RequestParam Map<String, String> params, Model model) {
        log.debug("Oauth2.0 redirect call params {}", params);
        if (ObjectUtils.isEmpty(params.get("code"))) {
            model.addAttribute("status", 500);
            model.addAttribute("message", params.get("error_description"));
            return Mono.just("redirect");
        }
        return this.authorize(params.get("state"), params.get("code"))
                .map(authorizationCode -> {
                    model.addAttribute("status", 200);
                    model.addAttribute("message", "Great! The AAD Authorization is successful. ");
                    return "redirect";
                }).onErrorResume(err -> {
                    log.error("Auth token error msg: {}", err.getMessage());
                    model.addAttribute("status", 500);
                    model.addAttribute("message", "Authorization error.");
                    return Mono.just("redirect");
                });

    }

    @ResponseBody
    @GetMapping("token")
    public Mono<TokenState> token(@RequestParam TokenState state) {
        log.debug("Refresh Token params tenantId is {}", state);
        return this.authService.getToken(state);
    }

}
